#!/usr/bin/env python
# -*- coding:utf-8 -*-

from scapy.all import *
import struct


path= 'D:/python/diameter/data/111.pcap'
pcap_pkts = rdpcap(path)

# i = 0
for packet in pcap_pkts:
    packet.show()
#     # print(packet['SCTPChunkData'].data)
#     decode_data=packet['SCTPChunkData'].data
#     strlist = decode_data.strip()
#     print(strlist)
#     length = decode_data[5:7]

sip = open(path,'rb')
string_data = sip.read()

packet_num = 0
packet_data = []
packet_header = {}
i =24
while(i<len(string_data)):
    #每一个数据包头16B字节
    packet_header['len'] = string_data[i+12:i+16]#找出该数据包的包长
    packet_len = struct.unpack('I',packet_header['len'])[0]
    packet_data.append(string_data[i+16:i+16+packet_len])#去除包头16B，留下以太帧数据
    i = i+ packet_len+ 16
    packetpdata=packet_data[packet_num]
    Ethernet_header = {}
    Ethernet_header['Etype'] = packetpdata[12:14]#找出以太帧内封装的类型
    print(packetpdata[12:14])
    if (Ethernet_header['Etype'].hex() =='8100'):  #判断是否为802.11
        vlandatas=packetpdata[14:]  #去除以太帧头14B，解封为IP包
        vlan_header = {}
        vlan_header['Protocol']=vlandatas[2:4]#找出802封装协议
        print(vlandatas)
        if(vlan_header['Protocol'].hex() == '0800'):  # 判断是否为IP包
            IPdatas = vlandatas[5:]  # 去除vlan头4B，解封为IP包
            IP_header = {}
            print(IPdatas)
            IP_header['Header_Len'] = IPdatas[14:15].hex()[1]  # 头部长度
            print(IPdatas[14:15].hex())
            print(IP_header['Header_Len'])
            IP_header['Protocol'] = IPdatas[5:11]  # 找出IP封装协议
            IP_headerlen = int(IP_header['Header_Len']) * 4  # IP包头部长度
            print(IP_headerlen)
            print(IP_header)
            if IP_header['Protocol'].hex()=='84': #判断是否为SCTP协议【132】
                SCTPdatas= IPdatas[IP_headerlen:]#去除IP头，解封为SCTP包
                print(IPdatas[IP_headerlen:])
                SCTP_header = {}
                SCTP_header['SrcPort']= SCTPdatas[0:2]#UDP端口号，用以筛选sip包【3868】

                if SCTP_header['SrcPort'].hex() == '0f1c':   #判断是否为DIA包,端口号5060
                    Diameter_length= SCTPdatas[2:3]#去除UDP头8B，留下sctp包
                    print(Diameter_length)
                    # decode_data = Diameter_length.decode()#解码sctp数据【0000】
                    # #strlist = decode_data.strip()#依照换行符拆分
                    #
                    # print('第', packet_num+1, '个sip包')
                    # print(strlist)#依次按行输出
                    # if SCTP_header['SrcPort'].hex() == '0f1c':  # 判断是否为sip包,端口号5060
                    #     Diameter_length = SCTPdatas[8:]  # 去除UDP头8B，留下sctp包
                    decode_data = Diameter_length.decode()  # 解码sctp数据【0000】


    packet_num += 1
